package br.com.jk.usuario.login;

import br.com.jk.master.Master;
import br.com.jk.usuario.Usuario;
import br.com.jk.usuario.UsuarioRn;
import br.com.jk.util.RNException;
import br.com.jk.util.StatusType.StatusUsuario;
import br.com.jk.util.Util;
import java.awt.event.KeyEvent;
import java.util.Arrays;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;

/**
 *
 * @author camilo
 */
public class LoginJDialog extends javax.swing.JDialog {

  public static Usuario usuarioLogado;

  /**
   * Creates new form LoginJDialog
   *
   * @param parent
   * @param modal
   */
  public LoginJDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    setLocationRelativeTo(null);
    showConfSenha(false);
    showNovaSenha(false);
  }

  /**
   * This method is called from within the constructor to initialize the form. WARNING: Do NOT
   * modify this code. The content of this method is always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;

    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jtfCod = new javax.swing.JTextField();
    jtfNome = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jpfSenha = new javax.swing.JPasswordField();
    jlNovaSenha = new javax.swing.JLabel();
    jpfNovaSenha = new javax.swing.JPasswordField();
    jlConfSenha = new javax.swing.JLabel();
    jpfConfSenha = new javax.swing.JPasswordField();
    jPanel1 = new javax.swing.JPanel();
    jbCancelar = new javax.swing.JButton();
    jbAlteraSenha = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
    setTitle("Autenticação");
    setModal(true);
    setResizable(false);
    getContentPane().setLayout(new java.awt.GridBagLayout());

    jLabel1.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel1.setText("Cod:");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
    getContentPane().add(jLabel1, gridBagConstraints);

    jLabel2.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel2.setText("Nome:");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
    gridBagConstraints.insets = new java.awt.Insets(0, 11, 0, 5);
    getContentPane().add(jLabel2, gridBagConstraints);

    jtfCod.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jtfCod.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    jtfCod.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfCodKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 1;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.ipadx = 44;
    gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
    getContentPane().add(jtfCod, gridBagConstraints);

    jtfNome.setEditable(false);
    jtfNome.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jtfNome.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    jtfNome.setToolTipText("Nome do Usuário");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 3;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.ipadx = 150;
    gridBagConstraints.insets = new java.awt.Insets(5, 0, 3, 10);
    getContentPane().add(jtfNome, gridBagConstraints);

    jLabel3.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel3.setText("Senha:");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.gridwidth = 3;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
    gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
    getContentPane().add(jLabel3, gridBagConstraints);

    jpfSenha.setEditable(false);
    jpfSenha.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jpfSenha.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    jpfSenha.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jpfSenhaKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 3;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.insets = new java.awt.Insets(3, 0, 3, 10);
    getContentPane().add(jpfSenha, gridBagConstraints);

    jlNovaSenha.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jlNovaSenha.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jlNovaSenha.setText("Nova Senha:");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.gridwidth = 3;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
    gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
    getContentPane().add(jlNovaSenha, gridBagConstraints);

    jpfNovaSenha.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jpfNovaSenha.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    jpfNovaSenha.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jpfNovaSenhaKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 3;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.insets = new java.awt.Insets(3, 0, 3, 10);
    getContentPane().add(jpfNovaSenha, gridBagConstraints);

    jlConfSenha.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jlConfSenha.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jlConfSenha.setText("Confirme a senha:");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.gridwidth = 3;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
    gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
    getContentPane().add(jlConfSenha, gridBagConstraints);

    jpfConfSenha.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jpfConfSenha.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    jpfConfSenha.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jpfConfSenhaKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 3;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.insets = new java.awt.Insets(3, 0, 3, 10);
    getContentPane().add(jpfConfSenha, gridBagConstraints);

    jPanel1.setLayout(new java.awt.GridLayout(1, 0, 20, 0));

    jbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/dialog-cancel.png"))); // NOI18N
    jbCancelar.setToolTipText("Cancelar");
    jbCancelar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbCancelarActionPerformed(evt);
      }
    });
    jPanel1.add(jbCancelar);

    jbAlteraSenha.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/key.png"))); // NOI18N
    jbAlteraSenha.setToolTipText("Alterar senha");
    jbAlteraSenha.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbAlteraSenhaActionPerformed(evt);
      }
    });
    jPanel1.add(jbAlteraSenha);

    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 4;
    gridBagConstraints.gridwidth = 4;
    gridBagConstraints.ipadx = 50;
    gridBagConstraints.insets = new java.awt.Insets(3, 0, 5, 0);
    getContentPane().add(jPanel1, gridBagConstraints);

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void jtfCodKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfCodKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jtfCod.getText() == null || jtfCod.getText().isEmpty()) {
        Util.msgErro("Você não digitou nenhum código, tente novamente.");
      } else {
        getNameUser(jtfCod.getText());
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
      encerrar();
    } else if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
      evt.setKeyCode(KeyEvent.VK_ENTER);
      jtfCodKeyPressed(evt);
    }
  }//GEN-LAST:event_jtfCodKeyPressed

  private void jbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCancelarActionPerformed
    if (jpfNovaSenha.isVisible()) {
      showNovaSenha(false);
    } else {
      encerrar();
    }
  }//GEN-LAST:event_jbCancelarActionPerformed

  private void jpfSenhaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jpfSenhaKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jpfSenha.getPassword() == null) {
        Util.msgErro("Você não digitou nenhuma senha, tente novamente.");
      } else {
        if (jpfNovaSenha.isVisible()) {
          jpfNovaSenha.requestFocus();
        } else if (jpfConfSenha.isVisible()) {
          jpfConfSenha.requestFocus();
        } else {
          validarSenha(jpfSenha);
        }
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
      encerrar();
    } else if (evt.getKeyCode() == KeyEvent.VK_UP) {
      Util.selJtf(jtfCod);
    } else if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
      evt.setKeyCode(KeyEvent.VK_ENTER);
      jpfSenhaKeyPressed(evt);
    }
  }//GEN-LAST:event_jpfSenhaKeyPressed

  private void jpfConfSenhaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jpfConfSenhaKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {

      JPasswordField jpass;
      if (jpfNovaSenha.isVisible()) {
        jpass = jpfNovaSenha;
      } else {
        jpass = jpfSenha;
      }

      if (validarConfirmacao(jpass)) {
        cadastrarSenha(jpass);
        entrar();
      }
    }
  }//GEN-LAST:event_jpfConfSenhaKeyPressed

  private void jbAlteraSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAlteraSenhaActionPerformed
    alterarSenha();
  }//GEN-LAST:event_jbAlteraSenhaActionPerformed

  private void jpfNovaSenhaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jpfNovaSenhaKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jpfConfSenha.requestFocus();
    }
  }//GEN-LAST:event_jpfNovaSenhaKeyPressed

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(LoginJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        LoginJDialog dialog = new LoginJDialog(new javax.swing.JFrame(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
          @Override
          public void windowClosing(java.awt.event.WindowEvent e) {
            System.exit(0);
          }
        });
        dialog.setVisible(true);
      }
    });
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JPanel jPanel1;
  private javax.swing.JButton jbAlteraSenha;
  private javax.swing.JButton jbCancelar;
  private javax.swing.JLabel jlConfSenha;
  private javax.swing.JLabel jlNovaSenha;
  private javax.swing.JPasswordField jpfConfSenha;
  private javax.swing.JPasswordField jpfNovaSenha;
  private javax.swing.JPasswordField jpfSenha;
  private javax.swing.JTextField jtfCod;
  private javax.swing.JTextField jtfNome;
  // End of variables declaration//GEN-END:variables

  void alterarSenha() {
    showNovaSenha(true);
    jtfCod.requestFocus();
    jbAlteraSenha.setEnabled(false);
  }

  private void validarSenha(JPasswordField jpass) {
    try {
      UsuarioRn rn = new UsuarioRn();
      if (rn.compararSenha(Util.getPasswordJpf(jpass), usuarioLogado)) {
        entrar();
      } else {
        Util.msgAdv("Não foi possível autenticar, tente novamente.");
        jtfCod.requestFocus();
      }
    } catch (RNException e) {
      Util.msgAdv(e, "Erro ao validar a senha");
    }
  }

  private void getNameUser(String codUser) {
    //cria instancias dos objetos
    UsuarioRn urn = new UsuarioRn();
//      busca o usuário no BD de acordo o parametro informado pelo usuário
    usuarioLogado = urn.carregarCod(codUser);

    if (usuarioLogado != null) {
      jtfNome.setText(usuarioLogado.getNome());
      jpfSenha.setEditable(true);
      jpfSenha.requestFocus();

      if (usuarioLogado.getSenha() == null) {
        Util.msgInfo("Esse é seu primeiro acesso, cadastre a sua senha");
        showNovaSenha(false);
        showConfSenha(true);
      }
    } else {
      Util.selJtf(jtfCod);
      jtfCod.requestFocus();
      Util.msgErro("Usuário inexistente");
    }
  }

  private void encerrar() {
    if (JOptionPane.showConfirmDialog(null, "Deseja realmente cancelar a autenticação?",
            "Autenticação", JOptionPane.YES_NO_OPTION)
            == JOptionPane.YES_OPTION) {
      this.dispose();
    } else {
      jtfCod.requestFocus();
    }
  }

  private void entrar() {
    if (usuarioLogado.getStatus() == StatusUsuario.ATIVO) {
      Master.usuarioLogado = usuarioLogado;
      Master.jlUser.setText(usuarioLogado.getCod() + " - " + usuarioLogado.getNomeCompleto());

      LoginPermissao.atribuiPermissoes(usuarioLogado);

      this.dispose();
    } else {
      Util.msgAdv("Não foi possível efetuar o login.\n\n"
              + "Usuário: " + usuarioLogado.getNomeCompleto()
              + "\nStatus: " + usuarioLogado.getStatus());
    }

  }

  private void showConfSenha(Boolean status) {
    jlConfSenha.setVisible(status);
    jpfConfSenha.setVisible(status);
  }

  private void showNovaSenha(Boolean status) {
    jlNovaSenha.setVisible(status);
    jpfNovaSenha.setVisible(status);
    showConfSenha(status);
  }

  private boolean validarConfirmacao(JPasswordField jpass) {
    System.out.println(jpfSenha.getPassword());
    System.out.println(jpfConfSenha.getPassword());

    if (Arrays.equals(jpass.getPassword(), jpfConfSenha.getPassword())) {
      return true;
    }

    if (jpass.getPassword() == jpfConfSenha.getPassword()) {
      return true;
    }
    return false;
  }

  private void cadastrarSenha(JPasswordField jpass) {
    UsuarioRn rn = new UsuarioRn();
    try {
      String senha = Util.getPasswordJpf(jpass);
      usuarioLogado.setSenha(rn.criptografar(senha));
      rn.salvar(usuarioLogado);
    } catch (RNException e) {
      Util.msgErro(e, "Erro ao cadastrar a senha");
    }
  }
}
